/*
 * Copyright 2013 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.security;
/**
 *  MyUserDetailServiceImpl.java
 *
 * @author Administrator
 */

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.fujitsu.nanjing.tieba.common.StringUtils;
import com.fujitsu.nanjing.tieba.constrant.CommonParamter;
import com.fujitsu.nanjing.tieba.ibator.CoreUser;
import com.fujitsu.nanjing.tieba.service.GroupService;
import com.fujitsu.nanjing.tieba.service.UserService;
@Component
public class MyUserDetailServiceImpl implements UserDetailsService {
	@Resource
	private UserService userService;

	@Resource
	private GroupService groupService;

	// 登入默认会调整到这里
	@SuppressWarnings("deprecation")
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		CoreUser user = usernameOremail(username);
		if (user == null) {
			throw new UsernameNotFoundException(username);
		} else {
			// TODO 兼容email登陆
			if (user.getLogincount() >= CommonParamter.ERROR_MAX_TIMES) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(user.getLoginexpire());
				calendar.add(Calendar.DAY_OF_MONTH, 1);
				if (new Date().after(calendar.getTime())) {
					user.setLogincount((byte) 0);
					userService.update(user);
				} else {
					throw new UsernameNotFoundException("该用户处于锁定状态,请与"
							+ calendar.getTime().toLocaleString() + "后重试！");
				}
			}
		}
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);
		// TODO可以在此处加上用户凭证过期等功能
		boolean enables = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		User userdetail = new User(user.getUserid(), StringUtils.decrypt(user
				.getPwd()), enables, accountNonExpired, credentialsNonExpired,
				accountNonLocked, grantedAuths);
		return userdetail;
	}

	// 取得用户的权限
	private Set<GrantedAuthority> obtionGrantedAuthorities(CoreUser user) {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		// 获取用户所属组
		// 获取用户所属组 组对象
		// 获取用户组对应 角色集合
		authSet.add(new SimpleGrantedAuthority(groupService.findById(
				user.getGroupid()).getGroupname()));
		return authSet;
	}
	/**
	 * 兼容邮箱登陆
	 */
	private CoreUser usernameOremail(String username) {
		CoreUser user = null;
		if (username != null) {
			if (username.indexOf("@") != -1) {
				System.out.println("email is " + username);
				user = userService.findUserByEmail(username);
			} else {
				System.out.println("username is " + username);
				user = userService.findById(username);
			}
		}
		return user;
	}
	/**
	 * 当用户没有登录时返回空
	 **/
	public UserDetails getUserDetails() {
		UserDetails user = null;
		if (SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal() instanceof UserDetails) {
			user = (UserDetails) SecurityContextHolder.getContext()
					.getAuthentication().getPrincipal();
		}
		return user;
	}
}
